package com.ethan.cj.ssm.controller;

import com.ethan.cj.ssm.entity.TestEntity;
import com.ethan.cj.ssm.service.TestService;
import com.ethan.cj.ssm.util.PageBean;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@Log4j
@RequestMapping("user")
public class TestController {
    @Autowired
    private TestService ts;

    @RequestMapping("home")
    public String toUserHome(
            @RequestParam("page") int page
            , @RequestParam(value = "name", required = false) String name
            , ModelMap modelMap) {
        PageBean<TestEntity> pb = new PageBean<>(page, 2);
        ts.pageList(pb, name);
        modelMap.addAttribute("pb", pb);
        modelMap.addAttribute("name", name);
        return "test/userhome";
    }

    @RequestMapping("/dologin")
    @ResponseBody
    public String dologin(String username, String password) {
        log.info("username: " + username + ", password: " + password);
        TestEntity user = ts.selectTestEntityByName(username);
        if (user != null) {
            if (username.equals(user.getUsername()) && password.equals(user.getPassword())) {
                return "yes";
            } else {
                return "no";
            }
        } else {
            return "null";
        }
    }

    @RequestMapping("delete")
    public String delete(int id) {
        ts.delete(id);
        return "redirect:/user/home?page=1";
    }

    @RequestMapping("insert")
    public String insert(String username, String password) {
        ts.insert(new TestEntity(username, password));
        return "redirect:/user/home?page=1";
    }

    @RequestMapping("update")
    public String update(int id, String password) {
        final TestEntity te = ts.selectTestEntityById(id);
        te.setPassword(password);
        ts.update(te);
        return "redirect:/user/home?page=1";
    }

}
